package io.github.eric.urpc.server;

import io.github.eric.urpc.core.conn.Connection;
import io.github.eric.urpc.core.util.ConstantsUtil;

import java.util.Collection;
import java.util.Collections;
import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.Collectors;

public class ConnectionGroup {
    private final String applicationName;
    private final Collection<Connection> connections;

    ConnectionGroup(String applicationName) {
        this.applicationName = applicationName;
        this.connections = ConcurrentHashMap.newKeySet();
    }

    public String getApplicationName() {
        return applicationName;
    }

    public void addConnection(Connection conn) {
        connections.add(conn);
    }

    public void removeConnection(Connection conn) {
        connections.remove(conn);
    }

    public Collection<Connection> getAllConnections() {
        return Collections.unmodifiableCollection(connections);
    }

    public Collection<Connection> getConnections(String applicationId) {
        return connections.stream().filter(conn -> applicationId.equals(conn.getAttribute(ConstantsUtil.APPLICATION_ID))).collect(Collectors.toList());
    }
}
